from app.models.database import db
from datetime import datetime

class SceneStep(db.Model):
    """场景步骤模型"""
    __tablename__ = 'scene_step'
    
    id = db.Column(db.Integer, primary_key=True)
    scene_id = db.Column(db.Integer, db.ForeignKey('scene.id'), nullable=False)
    parent_id = db.Column(db.Integer, db.ForeignKey('scene_step.id'))
    api_id = db.Column(db.Integer, db.ForeignKey('api_info.id'))
    type = db.Column(db.String(20), nullable=False, default='api')  # api, script, condition, loop
    name = db.Column(db.String(100))
    order = db.Column(db.Integer, default=0)  # 步骤顺序
    config = db.Column(db.JSON)  # 步骤配置，如脚本内容、条件表达式等
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关联到场景
    scene = db.relationship('Scene', back_populates='steps', foreign_keys=[scene_id])
    
    # 关联到API
    api = db.relationship('ApiInfo', back_populates='steps', foreign_keys=[api_id])
    
    # 关联到父步骤和子步骤
    parent = db.relationship('SceneStep', remote_side=[id], backref=db.backref('children', order_by=order))
    
    # 关联到执行步骤记录
    execution_records = db.relationship('ExecutionStepRecord', back_populates='step')
    
    def to_dict(self):
        result = {
            'id': self.id,
            'scene_id': self.scene_id,
            'parent_id': self.parent_id,
            'api_id': self.api_id,
            'type': self.type,
            'name': self.name,
            'order': self.order,
            'config': self.config or {},
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        
        # 添加API信息
        if self.api:
            result['api'] = {
                'id': self.api.id,
                'name': self.api.name,
                'method': self.api.method,
                'path': self.api.path
            }
        
        # 添加子步骤
        if self.type == 'condition':
            # 条件步骤，分为true和false两组子步骤
            true_steps = []
            false_steps = []
            
            for child in self.children:
                if child.order < len(self.config.get('true_steps', [])):
                    true_steps.append(child.to_dict())
                else:
                    false_steps.append(child.to_dict())
            
            result['true_steps'] = true_steps
            result['false_steps'] = false_steps
        
        elif self.type == 'loop':
            # 循环步骤，子步骤为循环体
            result['body_steps'] = [child.to_dict() for child in self.children]
        
        return result